"""
jackson.rttopt.utils

Random stuff used by rttopt.
"""

from jackson import debug

def CIDRstr(ip, mask):
    """
    Given an IP and a mask, returns the CIDR string for that IP, applying the
    mask. I.e, if given 192.168.1.1 and 24, returns 192.168.1.0/24; if given
    192.168.1.1 and 16, return 192.168.0.0/16
    """
    context = [__name__,'CIDRstr()']
    debug.enter(context, {'ip': ip, 'mask': mask}, 4)
    octets = ip.split('.')
    debug.comment(context, "octets: " + str(octets), 5)
    if len(octets) != 4:
        debug.exception(context, 'ValueError: IP does not contain exactly 4 octets')
        debug.leave(context, None, 4)
        raise ValueError('IP does not contain exactly 4 octets')
    if mask == 8 or mask == 16 or mask == 24:
        noctets = int(mask / 8)
        debug.comment(context, 'noctets: ' + str(noctets), 5)
        octets = octets[:noctets]
        octets.extend(gen_zeros(4 - noctets))
        base = '.'.join(octets)
        debug.comment(context, 'base: ' + base, 5)
        cidr_string = base + '/' + str(mask)
        debug.leave(context, {'cidr_string': cidr_string}, 4)
        return cidr_string
    else:
        debug.exception(context, 'ValueError: mask must be one of 8, 16, or 24')
        debug.leave(context, None, 4)
        raise ValueError('mask must be one of 8, 16, or 24')

def gen_zeros(n):
    """
    Generates a list of n '0' strings.
    @param n: how many zero strings to generate
    """
    retlist = []
    for i in range(0,n):
        retlist.append('0')
    return retlist
